package com.example.demo.design.mode.singleton;

/**
 * @author liweizhi
 * @date 2020/4/15 00:00
 */
public class SingletonTest006 {

    private static SingletonTest006 INSTANCE;

    public static SingletonTest006 getInstance() {
        if (INSTANCE == null) {
            // 模拟加载资源的过程,初始化比较慢
            synchronized (SingletonTest006.class) {
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                INSTANCE = new SingletonTest006();
            }
        }
        return INSTANCE;
    }

    private String name = "大黄";

    // 私有化构造方法
    private SingletonTest006() {

    }

    public String getName() {
        return name;
    }

    public void say() {
        System.out.println("hello~");
    }

    public static void main(String[] args) {
        // 通过输出hashcode,可以判断其是否是多线程安全的单例
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(SingletonTest006.getInstance().hashCode()))
                    .start();
        }
    }
}
